<template>
  <div>
    <!--面包屑导航区</h3>-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card class="box-card">
      <!--搜索框-->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入内容" v-model="username">
            <el-button slot="append" icon="el-icon-search" @click="searchByUsername"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="showAddDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <!--表格-->
      <el-table stripe :data="userList" border height="600px" style="width: 100%">
        <el-table-column width="60px" type="index"> </el-table-column>
        <el-table-column align="center" prop="username" label="姓名" width="180"> </el-table-column>
        <el-table-column align="center" prop="gender" label="性别">
          <template slot-scope="scope">
            {{ scope.row.gender ? '女' : '男' }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="phone" label=手机号>
        </el-table-column>
        <el-table-column align="center" prop="userRole" label="权限">
          <template slot-scope="scope">
            {{ showUserRole(scope.row.userRole)}}

          </template>
        </el-table-column>
        <el-table-column align="center" prop="userStatus" label="状态">
          <template slot-scope="scope">
            {{ scope.row.userStatus ? '封号' : '正常' }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createTime" width="100px" label=创建时间>
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="updateTime" width="100px" label=更新时间>
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column
            align="center"
            label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)" :disabled="scope.row.userRole===2"></el-button>
            </el-tooltip>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="deleteUser(scope.row.id)">
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" :disabled="scope.row.userRole===2"></el-button>
            </el-popconfirm>
            <el-popconfirm title="是否重置" @confirm="resetPassword(scope.row)">
              <el-button slot="reference" type="warning"  size="mini" :disabled="scope.row.userRole===2">重置密码</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--添加用户表单-->
      <el-dialog
          title="添加用户"
          :visible.sync="addDialogVisible"
          width="50%"
          @close="addDialogVisible = false">
        <el-form :model="addForm" label-width="120px" ref="addForm">
          <el-form-item label="用户名">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="addForm.userPassword"></el-input>
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input v-model="addForm.checkPassword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addUser">确定</el-button>
            <el-button @click="addDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>

      </el-dialog>
      <!-- 编辑用户信息框 -->
      <el-dialog
          title="编辑用户信息"
          :visible.sync="dialogVisible"
          width="50%"
          @close="dialogVisible = false"
      >
        <el-form :model="form" ref="form" label-width="120px">
          <!-- 表单内容，使用 v-model 绑定到 form 的属性上 -->
          <el-form-item label="用户名">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select placeholder="性别" v-model="form.gender"  >
              <el-option
                  v-for="o in getGander"
                  :key="o.value"
                  :label="o.label"
                  :value="o.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户权限">
            <el-select v-model="form.userRole" placeholder="请选择用户权限">
              <el-option
                  v-for="o in getUserRole"
                  :key="o.value"
                  :label="o.label"
                  :value="o.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户状态">
            <el-select v-model="form.userStatus">
              <el-option
                  v-for="o in getUserStatus"
                  :key="o.value"
                  :label="o.label"
                  :value="o.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateUser">确定</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: 'UserTable',
  data() {
    return {
      username: '',
      userList: [],
      dialogVisible: false, // 控制模态框的显示与隐藏
      addDialogVisible: false,
      form: {
        id: '',
        username: '',
        userPassword: '',
        phone: '',
        userRole: '',
        userStatus: ''
      },
      addForm: {
        username: '',
        userPassword: '',
        checkPassword: '',
      },
      userRole:'',
      getUserStatus:[
        {
          label:'正常',
          value:0
        },
        {
          label: '封号',
          value: 1
        }
      ],
      getUserRole:[
        {
          label:'普通用户',
          value:0
        },
        {
          label: '管理员',
          value: 1
        },
      ],
      getGander:[
        {
          label:'男',
          value:0
        },
        {
          label: '女',
          value: 1
        }
      ]
    }
  },
  computed: {

  },
  methods: {
    showUserRole(role){
      switch (role){
        case 0:
          return '普通用户'
        case 1:
          return '管理员'
        case 2:
          return '超级管理员'
      }
    },
    formatDate(dateTimeString) {
      const dateTime = new Date(dateTimeString);
      // 返回格式化后的日期时间字符串
      return dateTime.toISOString().slice(0, 19).replace('T', ' ');
    },
    async searchByUsername() {
      if (!this.username) {
        await this.getUserList()
        return
      }
      const url = `/api/user/search?username=${this.username}`;
      const {data: res} = await axios.get(url);
      this.userList = res.data;
    },
    async addUser() {
      const user = window.sessionStorage.getItem('user');
      this.userRole = JSON.parse(user);
      if (this.userRole.userRole!==1){
        this.$message.error("无添加用户权限")
        return}
      const {data: result} = await axios.post("/api/user/register", this.addForm)
      if (result.code === 0) {
        this.$message.success('添加成功')
        this.userList.push(this.addForm)
      } else
        this.$message.error(result.description)
      this.addDialogVisible = false
    },
    showEditDialog(row) {
      this.dialogVisible = true; // 显示模态框
      this.form = {...row}; // 使用展开运算符将当前行的数据复制到表单中
    },
    showAddDialog(row) {
      this.addDialogVisible = true;
      this.addForm = {...row}
    },
    async getUserList() {
      const {data: res} = await axios.get('/api/user/search')
      if(res.code === 0) {
        this.userList = res.data;
      }else
        this.$message.error(res.message)
    },
    async deleteUser(id) {
      try {
        const {data: response} = await axios.post(`/api/user/delete?id=${id}`);
        if (response.code !== 0) {
          this.$message.error('删除失败');
        } else {
          // 如果删除成功，你可能想要从 userList 中移除这个用户
          this.userList = this.userList.filter(user => user.id !== id);
          this.$message.success('删除成功');
        }
      } catch (error) {
        console.error('Error deleting user:', error);
        this.$message.error('删除失败，请稍后重试');
      }
    },
    async updateUser() {
      try {
        const {data: response} = await axios.post('/api/user/update', this.form)
        if (response.code === 0) {
          this.$message.success('用户信息更新成功');
          this.dialogVisible = false;
          await this.getUserList()
        } else {
          this.$message.error(response.description);
        }
      } catch (error) {
        console.error('Error updating user:', error);
        this.$message.error('更新用户信息时发生错误，请稍后重试');
      }
    },
    //重置密码
    async resetPassword(row){
      const {data: response} = await axios.get(`/api/user/resetUser?id=${row.id}`)
      if (response.code === 0) {
        return  this.$message.success('重置成功')
      }
      return this.$message.error(response.description||response.message||"未知错误")
    }
  },
  created() {
    this.getUserList();
  }
}
</script>
<style scoped>

</style>